#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi: ts=4 expandtab
#
# Copyright (C) 2012 KT
#
# Author: Choonho Son <choonho.son@kt.com>
#

__version__="1.0"
__all__ = []

import os.path
import urllib

from cloudcfg.lib.log import CloudLog
from ConfigParser import ConfigParser

class Cloud:
	__cfg__ = "cfg/cloudcfg"
	cfg = {}
	"""
	default class
	"""
	def __init__(self, cfg={}):
		self.logger = CloudLog().getLogger()
		self.config = ConfigParser()
		self.cfg = cfg
		#self.updateConfig(cfg)
		import cloudcfg
		self.pkgpath = cloudcfg.__path__[0]

	def updateConfig(self, cfg):
		"""
		@param cfg : cfg dictionary (key = section.option)
		update self.config
		"""
		cfg_path = os.path.join(self.pkgpath, self.__cfg__)
		self.logger.debug("cfg path:%s" % cfg_path)
		self.config.read(cfg_path)
		keys = cfg.keys()
		for key in keys:
			(section,option) = key.split(".")
			self.config.set(section,option,cfg[key])
		
		msg = "\n"
		for section in self.config.sections():
			msg = msg + "[%s]\n" % section
			for option in self.config.options(section):
				msg = msg + "%s = %s\n" % (option, self.config.get(section,option))
		self.logger.debug(msg)

	def getSectionParams(self, section):
		params = {}
		for option in self.config.options(section):
			params[option] = self.config.get(section,option)
		return params
	
	def install(self,cfg):
		"""
       		default installation for hpc
       		"""
       		# fetch userData
		self.updateConfig(cfg)
		

	def getVirtualRouterIP(self):
		"""
		find Virtual Router IP address from dhcp info
		@return: (Virtual Router IP, Domain name) (fail: False)
		"""
		if sys.version_info < (2,6):
			(OS,ver,id) = platform.dist()
		else:
			(OS,ver,id) = platform.linux_distribution()
				
		eth = os.path.join(DhcpDir[OS], 'dhclient-eth0.leases')
		#check file exist

		self.logger.debug("Interface path:%s" % eth)
		fp = open(eth,'r')
		ip_pattern = r'(option dhcp-server-identifier) (\d+.\d+.\d+.\d+)'
		domain_pattern = r'(option domain-name) "(\S+)"'
		vrip = ''
		domain = ''
		for line in fp:
			token = re.findall(ip_pattern, line)
			token2 = re.findall(domain_pattern, line)
			if len(token) == 1:
				(k, vrip) = token[0]
			if len(token2) == 1:
				(k, domain) = token2[0]

		self.logger.info("Virtual Router IP: %s" % vrip)
		self.logger.info("Domain name : %s" % domain)
		self.common['domain'] = domain
		return (vrip, domain)
								
	def fetchVMID(self):
		"""
		fetch vm-id from Virtual Router
		"""
		(vrip, domain) = self.getVirtualRouterIP()
		url = "http://%s/latest/vm-id" % vrip
		self.logger.debug("Fetch vm-id from %s" % url)
		try:
			f = urllib.urlopen(url)
			vmid = f.read()
			self.logger.debug("vm-id:%s" % vmid)
			return vmid
			
		except:
			return -1


	def help(self):
		"""
		High Performance Cluster Computing Service
		Provided by KT Ucloud
		"""

def install(msg):
	inst = Cloud()
	inst.install(msg)
	
